package helper

import (
	"errors"
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"

	"gitee.com/go-caipu-team/go-caipu-plugin-sdk/pkg/constant"
)

func ErrorWithDetail(ctx *gin.Context, code int, msgKey string, err error) {
	res := Response{
		Code:    code,
		Msg:     "",
		Success: false,
	}
	if msgKey == constant.ErrTypeInternalServer {
		switch {
		case errors.Is(err, constant.ErrRecordExist):
			res.Msg = "ErrRecordExist"
		case errors.Is(constant.ErrRecordNotFound, err):
			res.Msg = "ErrRecordNotFound"
		case errors.Is(constant.ErrInvalidParams, err):
			res.Msg = "ErrInvalidParams"
		case errors.Is(constant.ErrStructTransform, err):
			res.Msg = fmt.Sprintf("ErrStructTransform,detail:%s", err)
		case errors.Is(constant.ErrInitialPassword, err):
			res.Msg = fmt.Sprintf("ErrInitialPassword,detail:%s", err)
		default:
			res.Msg = fmt.Sprintf("%s,detail:%s", msgKey, err)
		}

		ctx.JSON(http.StatusOK, res)
		ctx.Abort()
		return
	}
	res.Msg = fmt.Sprintf("%s,detail:%s", msgKey, err)
	ctx.JSON(http.StatusOK, res)
	ctx.Abort()
}
func SuccessWithData(ctx *gin.Context, data interface{}) {
	if data == nil {
		data = gin.H{}
	}
	res := Response{
		Code:      constant.CodeSuccess,
		Data:      data,
		Success:   true,
		TimeStamp: time.Now().Unix() * 1000,
	}
	ctx.JSON(http.StatusOK, res)
	ctx.Abort()
}
func SuccessWithOutData(ctx *gin.Context) {
	res := Response{
		Code:    constant.CodeSuccess,
		Msg:     "success",
		Success: true,
	}
	ctx.JSON(http.StatusOK, res)
	ctx.Abort()
}

func SuccessWithMsg(ctx *gin.Context, msg string) {
	res := Response{
		Code:    constant.CodeSuccess,
		Msg:     msg,
		Success: true,
	}
	ctx.JSON(http.StatusOK, res)
	ctx.Abort()
}
func GetParamStringID(c *gin.Context) (string, error) {
	idParam, ok := c.Params.Get("id")
	if !ok {
		return "", errors.New("error id in path")
	}
	return idParam, nil
}
